from machine import I2C, Pin, SPI
import usocket
import network
import time
import os
import gc


def File_CM(old_path, new_path, mode):
    o = open(old_path)
    n = open(new_path, "w")
    n.write(o.read())
    o.close()
    n.close()
    if mode == "copy":
        pass
    elif mode == "move":
        os.remove(old_path)


def Install_File(path="/sdc"):
    Files = os.listdir(path)
    for i in Files:
        if "_libs.py" in i:
            old_path = path + "/" + i
            new_path = "/sdc/lib/" + i.split("_")[0] + "." + i.split(".")[1]
            File_CM(old_path, new_path, "move")
        elif "_datas." in i:
            old_path = path + "/" + i
            new_path = "/sdc/data/" + i.split("_")[0] + "." + i.split(".")[1]
            File_CM(old_path, new_path, "move")


def config(search, path = "/sdc/data/login.cot"):
    for line in open(path):
        if line[-1:] == "\n":
            line = line[:-1]
        if "=" in line:
            sc = line.split("=", 1)[0].strip()
            data = line.split("=", 1)[1].strip()
            if search == sc:
                if data == "_None":
                    return " "
                else:
                    return data
    return None


def re(number):
    number = str(number).encode()
    return number


def Tree_Connect(Host, Port, User, Key):
    str(Host, User, Key)
    int(Port)
    login = usocket.socket()
    login.connect((Host, Port))
    msg = "1131-" + User + "-" + Key
    login.send(msg.encode())
    data = login.recv(128).decode()
    if data[0:3] != "200":
        return False
    login.close()
    data = data.split("-")
    Tree = usocket.socket()
    Tree.connect((Host, int(data[1])))
    Tree.send(re(100))
    data = Tree.recv(128).decode()
    return Tree


def Base_Connect(Tree, Base, Code):
    if Tree == False:
        return False
    command = "140-" + Base + "-" + Code
    Tree.send(command.encode())
    data = Tree.recv(128).decode()
    if data == "300":
        LED = Pin(2, Pin.OUT, value=1)
        LED.value(1)
        time.sleep_ms(300)
        LED.value(0)
        return True
    else:
        return False


def WLAN_Connect(Name, Key):
    str(Name)
    str(Key)
    if len(Key) >= 8:
        WIFI_LED = Pin(2, Pin.OUT, value=1)
        wlan = network.WLAN(network.STA_IF)
        wlan.active(True)
        start_time = time.time()
        if not wlan.isconnected():
            wlan.connect(Name, Key)
            while not wlan.isconnected():
                WIFI_LED.value(0)
                time.sleep_ms(300)
                WIFI_LED.value(1)
                time.sleep_ms(300)
                if time.time() - start_time > 15:
                    return False
        if wlan.isconnected():
            WIFI_LED.value(0)
            return wlan
